/* 2017-12-7 10:33:50 | 修改 木遥（QQ：516584683） */
//loading bar
var loadingBar = document.getElementById('loadbar');
var oldTime = new Date().getTime();
var thisWidget = {};
var dataT;

function run() {
    var curTime = new Date().getTime();
    if (curTime - oldTime >= 3500) {
        loadingBar.className = "";
        if (curTime - oldTime >= 3550) {
            loadingBar.className = "ins";
            oldTime = curTime;
        }
    }
    if (Window.LOADING_FLAG == true) {
        clearInterval(loadIdx);
    }
}

function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg); //匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; //返回参数值
}

function loaderOK() {
    $("#loadOverlay").hide();
    $('#loadbar').removeClass('ins');
    Window.LOADING_FLAG = true;
}
var loadIdx = setInterval(run, 100);


//地图
$(document).ready(function() {
    if (!mars3d.util.webglreport()) {
        toastr.error('系统检测到您当前使用的浏览器WebGL功能无效');
        layer.open({
            type: 1,
            title: "当前浏览器WebGL功能无效",
            skin: "layer-mars-dialog animation-scale-up",
            resize: false,
            area: ['600px', '200px'], //宽高
            content: '<div style="margin: 20px;"><h3>系统检测到您使用的浏览器WebGL功能无效！</h3>  <p>1、请您检查浏览器版本，安装使用最新版chrome、火狐或IE11以上浏览器！</p> <p>2、WebGL支持取决于GPU支持，请保证客户端电脑已安装最新显卡驱动程序！</p><p>3、如果上两步骤没有解决问题，说明您的电脑需要更换了！</p></div>'
        });
    }
    initUI();
    initMap();
});

function removeMask() {
    $("#mask").remove();
}

var viewer;
//初始化地图
function initMap() {
    var request = haoutil.system.getRequest();

    var configfile = "config/sceneManage.json";
    if (request.config)
        configfile = request.config;

    haoutil.loading.show();

    var r = new Cesium.Resource({
        url: "http://10.253.102.69/gw/ESRI/Map/SZ_IMG02_2019/{z}/{x}/{y}",
        headers: {
            'szvsud-license-key': 'E7YieQ1tH6Q4CjoZAmI98Fc5mbayuHfXAjkKyZS3bZM=',
        },
    });

    mars3d.createMap({
        id: 'cesiumContainer',
        url: configfile + "?time=20190418",
        imageryProvider: new Cesium.UrlTemplateImageryProvider({
            url: r
        }),
        // infoBox: false,     //是否显示点击要素之后显示的信息  【也可以在config.json中配置】
        //sceneMode: Cesium.SceneMode.SCENE2D,
        layerToMap: layerToMap,
        success: function(_viewer, gisdata, jsondata) { //地图成功加载完成后执行
            //欢迎UI关闭处理
            setTimeout(removeMask, 3000);
            loaderOK();
            haoutil.loading.hide();

            //记录viewer
            viewer = _viewer;

            //初始化widget管理器
            var hasAnimation = true;
            if (haoutil.isutil.isNotNull(request.widget)) {
                jsondata.widget.widgetsAtStart.push({
                    uri: request.widget,
                    request: request
                });
                hasAnimation = false;
            }
            mars3d.widget.init(_viewer, jsondata.widget);

            //如果有xyz传参，进行定位
            if (haoutil.isutil.isNotNull(request.x) &&
                haoutil.isutil.isNotNull(request.y)) {
                viewer.mars.centerAt(request, { duration: 0, isWgs84: true });
            }

            // if (hasAnimation)
            //     viewer.mars.openFlyAnimation();//开场动画

            initWork(_viewer);
            testWork(_viewer); //测试专用


            //代码添加
            var scene_id = getUrlParam("sceneId"); //场景ID

            dealQingxie(_viewer)

            defaultAngle(); //场景初始视角
            sceneNavigate(); //场景导览
            // getSceneData(scene_id);//获取场景图层数据
            scenePreview(getSceneData(scene_id)); //预览场景

        }
    });
}

function dealQingxie(ALLviewer) {
    viewer.mars.updateTerrainProvider(false);
    const mapurl = new Cesium.Resource({
        url: "http://10.190.54.56:7763/TILE_3D_MODEL/futian/tileset.json",
        headers: { "szvsud-license-key": "eTG1UGBSvr4HdQnLecWX1s8GA4NWjLe8Rp8eI9ztla05D5mPYyi3rvVRX0RGjm5G" }
    });
    new Cesium.Cesium3DTileset({
        url: mapurl, // 你的倾斜摄影服务发布地址  // "http://localhost/xmhtileset/tileset.json",
        skipLevelOfDetail: true,
        preferLeaves: true,
        maximumScreenSpaceError: 16,
        skipLevels: 1,
    }).readyPromise.then(tileSet => {
        console.log('成功加载')
        viewer.scene.primitives.add(tileSet); // 将倾斜摄影实体加载到地图上

        viewer.zoomTo(tileSet);
    });
}

//场景导览，加载默认导览路径
function sceneNavigate() {
    var scene_id = getUrlParam("sceneId"); //场景ID
    $.ajax({
        url: "/one/scene/navigation/route/all" + '?sceneId=' + scene_id,
        type: "GET",
        dataType: "json",
        contentType: "application/json; charset=UTF-8",
        success: function(result) {
            if (result.errorCode === '401') {
                loginStatusIntercept(result.msg)
                return
            }
            if (result.errorCode == 0) {
                var roamList = result.data;
                for (var i = 0, len = roamList.length; i < len; i++) {
                    var list = roamList[i].isDefault;
                    var listRoute = roamList[i].navigationContent;
                    var listRouteObj = JSON.parse(listRoute);
                    //判断是否为默认导览路径
                    if (list === true) {
                        //场景管理页面，点击预览按钮时，传参隐藏弹框里面的停止漫游按钮
                        toRoamFly(listRouteObj, true);
                        break;
                    } else {}
                }
            } else {
                layer.msg("获取数据失败");
            }
        }
    });
}
//飞行路径
function toRoamFly(data, hide) {
    //场景管理页面，点击预览按钮时，传参隐藏弹框里面的停止漫游按钮
    mars3d.widget.activate({
        uri: 'widgets/roamFly/widget.js',
        data: data,
        hide
    });
}
//图层预览
function load3Dtiles(dataUrl) {
    //加载三维模型，此方法可设置相机初始视角
    var tileset = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
        url: dataUrl,
        maximumScreenSpaceError: 2,
        dynamicScreenSpaceError: true,
    }));
    tileset.modelMatrix  =  Cesium.Matrix4.fromArray([
        1.0,  0.0,  0.0,  0.0,
        0.0,  1.0,  0.0,  0.0,
        0.0,  0.0,  1.0,  0.0,
        0.0,  0.0,  0.0,  1.0
    ]);
    // viewer.scene.primitives.add(tileset);
    tileset.readyPromise.then(function(tileset) {
        viewer.scene.primitives.add(tileset);
        viewer.zoomTo(tileset, new Cesium.HeadingPitchRange(0.5, -0.5, tileset.boundingSphere.radius * 0.5));
    }).otherwise(function(error) {
        console.log(error);
    });
    // debugger
    // viewer.scene.primitives.remove(tileset);
    return tileset;

}
//自定义图层地图服务要素图层预览
/*
    loadGeoJson:function(dataUrl) {
          var kd = Cesium.GeoJsonDataSource.load(dataUrl, {
            // strokeWidth: 3,
            // clampToGround: true,
            // stroke: Cesium.Color.WHITE,
          });
          var oneLayer = viewer.dataSources.add(kd).then(function (dataCtrl) {
            // data = dataCtrl;
            // data._groundPrimitives.show = false;
          });
          window.viewer.zoomTo(oneLayer);
          window.viewer.dataSources.remove(oneLayer);
          window.viewer.dataSources.remove(kd);

        },*/
function loadGeoJson(dataUrl) {

    var data = window.viewer.dataSources.add(Cesium.GeoJsonDataSource.load(dataUrl, {
        // stroke: Cesium.Color.HOTPINK,//颜色样式渲染
        // fill: Cesium.Color.PINK,
        // strokeWidth: 3,
        //markerSymbol: './gis/data/geojson/render.png'
    }));
    window.viewer.zoomTo(data);
    // window.viewer.dataSources.removeAll();
}

//空间模型geojson数据加载
function load3DGeoJson(json) {
    this.drawControl = new mars3d.Draw(this.viewer, {
        hasEdit: false,
        nameTooltip: true,
    });
    this.drawControl.jsonToEntity(json, true, true); //视角定位指向实体
}

function clear() {
    window.viewer.dataSources.removeAll();
    window.viewer.scene.primitives.removeAll();
    window.viewer.dataSource.entities.removeAll();
    // this.dataSource.entities.removeAll();
}

function removeGeoJson() {
    window.viewer.dataSources.removeAll();
}

function remove3DGeoJson() {
    window.viewer.dataSources.removeAll();
    // this.dataSource.entities.removeAll();
}

function remove3Dtiles() {
    window.viewer.scene.primitives.removeAll();
}

//创建空间模型
function spatialModelCreate() {
    mars3d.widget.activate({
        uri: 'view/sceneManage/spatialModelCreate/widget.js',
        name: "创建空间模型"
    });
}

//空间模型创建后，弹框点击保存事件
function get3DGeoJson() {
    /*   this.drawControl = new mars3d.Draw(this.viewer, {
           hasEdit: false,
           nameTooltip: true,
       });
       return this.drawControl.toGeoJSON();*/
    var spatialModelCreate = mars3d.widget.getClass('view/sceneManage/spatialModelCreate/widget.js');
    return spatialModelCreate.getGeoJson();
}

//空间模型创建后，关闭弹框
function close_spatialModelCreate() {
    mars3d.widget.disable(
        'view/sceneManage/spatialModelCreate/widget.js', false
    );
}

//默认初始视角
function defaultAngle() {
    var scene_id = getUrlParam("sceneId"); //场景ID
    function showExtent(cfg) {
        console.log('书签定位：' + JSON.stringify(cfg));
        window.viewer.mars.centerAt(cfg, { isWgs84: true });
    }

    $.ajax({
        url: "/one/scene/detail",
        type: "GET",
        dataType: "json",
        contentType: "application/json; charset=UTF-8",
        data: { id: scene_id },
        success: function(result) {
            if (result.errorCode === '401') {
                loginStatusIntercept(result.msg)
                return
            }
            var getExtent = result.data.angle;
            var bookmarkGet = JSON.parse(getExtent);
            showExtent(bookmarkGet);
        }
    });
}
//场景图层加载
function getSceneData(scene_id) {
    $.ajax({
        url: '/one/scene/element/list/all' + '?sceneId=' + scene_id,
        dataType: 'json',
        type: 'get',
        async: false,
        // data:JSON.stringify({sceneId:featureId}),
        success: function(result) {
            if (result.errorCode === '401') {
                loginStatusIntercept(result.msg)
                return
            }
            var treeData = result.data;
            dataT = treeData;
            console.log(dataT);
        }
    });
    return dataT;
}
//场景图层加载
function scenePreview(sceneData) {
    for (var i = 0; i < sceneData.length; i++) {
        var data = sceneData[i];
        $.ajax({
            url: "/one/scene/elementInfo",
            type: "GET",
            dataType: "json",
            contentType: "application/json; charset=UTF-8",
            data: { id: data.id },
            success: function(result) {
                if (result.errorCode === '401') {
                    loginStatusIntercept(result.msg)
                    return
                }
                var previewUrl = result.data.elementContent;
                var jumpUrl = "";
                // 判断添加的服务地址是否为geoserver发布的服务
                if (previewUrl.indexOf("geoserver") != -1) {
                    jumpUrl = previewUrl; //jumpUrl通过geoserver截断解决跨域问题
                    // jumpUrl =  previewUrl.substr(previewUrl.indexOf("geoserver")-1);//jumpUrl通过geoserver截断解决跨域问题
                    loadGeoJson(jumpUrl); //调用iframe页面中的函数
                } else if (previewUrl.indexOf("geoserver") == -1) {
                    //jumpUrl字符串中不含有geoserver字符串
                    if (previewUrl.indexOf("http://") != -1) {
                        load3Dtiles(previewUrl);
                    } else {
                        load3DGeoJson(previewUrl);
                    }
                }
            }
        });
    }
}


//UI界面相关
function initUI() {
    // haoutil.oneMsg('首次访问系统无缓存会略慢，请耐心等待！', 'load3d_tip');


}


//当前页面业务相关
function initWork(viewer) {
    // haoutil.oneMsg('如果未出现地球，是因为地形加载失败，请刷新重新加载！', 'terrain_tip');

    // 禁用默认的实体双击动作。
    viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
    viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);

    //webgl渲染失败后，刷新页面
    //viewer.scene.renderError.addEventListener(function (scene, error) {
    //    window.location.reload();
    //});


    //移动设备上禁掉以下几个选项，可以相对更加流畅
    if (!haoutil.system.isPCBroswer()) {
        viewer.targetFrameRate = 20; //限制帧率
        viewer.requestRenderMode = true; //取消实时渲染
        viewer.scene.fog.enable = false;
        viewer.scene.skyAtmosphere.show = false;
        viewer.scene.fxaa = false;
    }

    //IE浏览器优化
    if (window.navigator.userAgent.toLowerCase().indexOf("msie") >= 0) {
        viewer.targetFrameRate = 20; //限制帧率
        viewer.requestRenderMode = true; //取消实时渲染
    }

    //更改配置，性能优化
    viewer.scene.logarithmicDepthBuffer = false;

    //二三维切换不用动画
    if (viewer.sceneModePicker)
        viewer.sceneModePicker.viewModel.duration = 0.0;

    //设置操作习惯,更换中键和右键
    //viewer.scene.screenSpaceCameraController.tiltEventTypes = [
    //    Cesium.CameraEventType.RIGHT_DRAG, Cesium.CameraEventType.PINCH,
    //    { eventType: Cesium.CameraEventType.LEFT_DRAG, modifier: Cesium.KeyboardEventModifier.CTRL },
    //    { eventType: Cesium.CameraEventType.RIGHT_DRAG, modifier: Cesium.KeyboardEventModifier.CTRL }
    //];
    //viewer.scene.screenSpaceCameraController.zoomEventTypes = [Cesium.CameraEventType.MIDDLE_DRAG, Cesium.CameraEventType.WHEEL, Cesium.CameraEventType.PINCH];


    //3dtiles模型的单体化高亮，在ex/featureViewer.js处理
    featureViewer.install(viewer);


}

//config中非底层类库封装类，可以在此加入进行实例化
function layerToMap(item, viewer, layer) {
    switch (item.type) {
        //case "s3m"://超图S3M数据加载
        //    return new S3MLayer(item, viewer);
        //    break;
    }
}


//测试一些功能
function testWork(viewer) {
    //绑定confgi.json标绘类型图层 单击事件
    // var layerWork = this.viewer.mars.getLayer(303011, 'id');
    // layerWork.config.click =function(entity){
    //     //var name =entity.attribute.name;

    //     mars3d.widget.activate({
    //         uri: 'widgetsTS/qyDetailsView/widget.js',
    //         attribute: entity.attribute,
    //     });
    // }

}

//绑定图层管理有2种添加方式
/**
    第1种是框架支持的配置信息的，按照下面方式添加
    var json = {
        "pid": 40,
        "name": "代码添加图层test",
        "type": "wms",
        "url": "http://gisserver.tianditu.com/TDTService/region/wms",
        "layers": "030100",
        "parameters": {
            "transparent": "true",
            "format": "image/png"
        },
        "center": { "y": 17.571877, "x": 114.258325, "z": 6591684.1, "heading": 352.3, "pitch": -74.3, "roll": 0.1 },
        "visible": true
    };
    mars3d.layer.createLayer(json, viewer);
    bindToLayerControl(json);
**/

/** 第2种是完全自定义的，在回调方法中写自己相关代码，可参考widgetsTS\qyPoint\widgts.js代码
bindToLayerControl({
    pid: 30,
    name: '企业',
    mydata:null, //自行赋值
    visible: true,
    onAdd: function () {//显示回调
        //这里把数据this.mydata添加到地图上
    },
    onRemove: function () {//隐藏回调
        //这里把数据this.mydata从地图上移除

    },
    onCenterAt: function (duration) {//定位回调

    },
});
**/

//绑定图层管理
function bindToLayerControl(options) {
    if (options._layer == null) {
        var _visible = options.visible;
        delete options.visible;

        var layer = new mars3d.layer.BaseLayer(options, viewer);
        layer._visible = _visible;
        options._layer = layer;
    }

    var manageLayersWidget = mars3d.widget.getClass('widgets/manageLayers/widget.js');
    if (manageLayersWidget) {
        manageLayersWidget.addOverlay(options);
    } else {
        viewer.gisdata.config.operationallayers.push(options);
    }
    return options._layer;
}
//取消绑定图层管理
function unbindLayerControl(name) {
    var manageLayersWidget = mars3d.widget.getClass('widgets/manageLayers/widget.js');
    if (manageLayersWidget) {
        manageLayersWidget.removeLayer(name);
    } else {
        var operationallayersCfg = viewer.gisdata.config.operationallayers;
        for (var i = 0; i < operationallayersCfg.length; i++) {
            var item = operationallayersCfg[i];
            if (item.name == name) {
                operationallayersCfg.splice(i, 1);
                break;
            }
        }
    }
}

//外部页面调用
function activateWidget(item) {
    mars3d.widget.activate(item);
}

function disableWidget(item) {
    mars3d.widget.disable(item);
}

function activateFunByMenu(fun) {
    eval(fun);
}

var featureViewer = {
    showInfo: false, //是否开启单击显示属性
    colorHighlight: Cesium.Color.YELLOW,
    colorSelected: Cesium.Color.LIME,
    getBimAttr: function(pickedFeature) {
        if (!pickedFeature.tileset.properties || !pickedFeature.tileset.properties.length)
            return false;

        var fileParams;

        //如果有文件名，那么依据文件名
        if (pickedFeature.hasProperty("file")) {
            var file = pickedFeature.getProperty("file");

            for (var i = 0; i < pickedFeature.tileset.properties.length; i++) {
                var params = pickedFeature.tileset.properties[i];
                if (params.file == file) {
                    fileParams = params.params;
                }
            }
        }
        //直接取第一个
        else {
            fileParams = pickedFeature.tileset.properties[0].params;
        }

        if (!fileParams)
            return false;



        // 名称和 id
        var arrAttr = [];

        function addItem(name, value) {
            if (value != null && value != "" && value != 0)
                arrAttr.push({ name: name, value: value });
        }

        if (pickedFeature.hasProperty("id"))
            addItem('ID', pickedFeature.getProperty("id"));
        if (pickedFeature.hasProperty("name"))
            addItem('名称', pickedFeature.getProperty("name"));
        if (pickedFeature.hasProperty("LevelName"))
            addItem('楼层', pickedFeature.getProperty("LevelName"));
        if (pickedFeature.hasProperty("CategoryName"))
            addItem('分类', pickedFeature.getProperty("CategoryName"));
        if (pickedFeature.hasProperty("FamilyName"))
            addItem('族', pickedFeature.getProperty("FamilyName"));
        if (pickedFeature.hasProperty("FamilySymbolName"))
            addItem('族类型', pickedFeature.getProperty("FamilySymbolName"));
        if (pickedFeature.hasProperty("file"))
            addItem('文件名', pickedFeature.getProperty("file"));



        //依据group分类
        var groups = {};
        var names = pickedFeature._content.batchTable.getPropertyNames(pickedFeature._batchId);
        for (var k = 0; k < names.length; k++) {
            var n = names[k];
            if (n == "_properties") { //对于这种属性

                var properties = pickedFeature.getProperty(n);

                try {
                    var sets = JSON.parse(properties);

                    for (var b = 0; b < sets.length; b++) {
                        var set = sets[b];

                        var rows = groups[set.name];
                        if (!rows) rows = [];

                        for (var j = 0; j < set.properties.length; j++) {
                            var p = set.properties[j];
                            if (!p.value) continue;

                            var row = { name: p.name, value: p.value };
                            rows.push(row);
                        }
                        groups[set.name] = rows;

                    }
                } catch (ex) {
                    console.log("parse _properties failed:" + ex);
                }
            } else { //其他属性
                var name = n,
                    value = pickedFeature.getProperty(n);

                var defp;
                for (var j = 0; j < fileParams.length; j++) {
                    var fp = fileParams[j];
                    if (name == fp.name) {
                        defp = fp;
                        break;
                    }
                }
                if (!defp) continue;

                var rows = groups[defp.group];
                if (!rows) rows = [];

                var val = value;
                if (defp.type == "YesNo")
                    val = value == 1 ? '是' : '否';
                if (defp.type == "Length")
                    val = (value * 0.3048).toFixed(2) + 'm';
                if (defp.type == "Area")
                    val = (value * 0.3048 * 0.3048).toFixed(2) + '㎡';
                if (defp.type == "Volume")
                    val = (value * 0.3048 * 0.3048 * 0.3048).toFixed(2) + 'm³';

                if (!val) continue;

                var row = { name: defp.name, value: val };
                rows.push(row);
                groups[defp.group] = rows;
            }

        }


        function groupName(group) {
            if (group == "PG_IDENTITY_DATA")
                return "标识数据";
            if (group == "PG_GEOMETRY")
                return "尺寸标注";
            if (group == "PG_PHASING")
                return "阶段化";
            if (group == "PG_CONSTRAINTS")
                return "约束";
            if (group == "INVALID")
                return '其他';
            if (group == "PG_MATERIALS")
                return '材质和装饰';
            if (group == "PG_CONSTRUCTION")
                return '构造';
            return group;
        }

        for (group in groups) {
            arrAttr.push({ type: 'group', name: groupName(group) });

            var rows = groups[group];
            for (var i = 0; i < rows.length; i++) {
                arrAttr = arrAttr.concat(rows[i]);
            }
        }

        return arrAttr;

    },
    install: function(viewer) {
        this.viewer = viewer;

        var nameOverlay = document.createElement('div');
        viewer.container.appendChild(nameOverlay);
        //nameOverlay.className = 'backdrop';
        nameOverlay.style.display = 'none';
        nameOverlay.style.position = 'absolute';
        nameOverlay.style.bottom = '0';
        nameOverlay.style.left = '0';
        nameOverlay.style.color = '#ffffff';
        nameOverlay.style['pointer-events'] = 'none';
        nameOverlay.style.padding = '4px';
        nameOverlay.style.backgroundColor = 'black';
        this.nameOverlay = nameOverlay;

        var selected = {
            feature: undefined,
            originalColor: new Cesium.Color()
        };
        var highlighted = {
            feature: undefined,
            originalColor: new Cesium.Color()
        };
        var selectedEntity = new Cesium.Entity();


        var self = this;

        this.restoreHighlight = function() {
            if (Cesium.defined(highlighted.feature)) {
                try {
                    highlighted.feature.color = highlighted.originalColor;
                } catch (ex) {}
                highlighted.feature = undefined;
            }
        };
        this.onMouseMove = function(event) {
            self.restoreHighlight();

            // Pick a new feature
            var pickedFeature = viewer.scene.pick(event.endPosition);
            if (!Cesium.defined(pickedFeature)) {
                nameOverlay.style.display = 'none';
                return;
            }

            if (!Cesium.defined(pickedFeature.getProperty)) {
                nameOverlay.style.display = 'none';
                return;
            }
            // A feature was picked, so show it's overlay content

            var name = pickedFeature.getProperty('name');
            if (!Cesium.defined(name)) {
                name = pickedFeature.getProperty('id');
            }
            if (!Cesium.defined(name)) {
                name = pickedFeature.getProperty('ID');
            }
            if (!name || name == '') {
                nameOverlay.style.display = 'none';
                return;
            }

            nameOverlay.style.display = 'block';
            nameOverlay.style.bottom = viewer.canvas.clientHeight - event.endPosition.y + 'px';
            nameOverlay.style.left = event.endPosition.x + 'px';
            nameOverlay.textContent = name;

            // Highlight the feature if it's not already selected.
            if (pickedFeature !== selected.feature) {
                highlighted.feature = pickedFeature;
                Cesium.Color.clone(pickedFeature.color, highlighted.originalColor);
                pickedFeature.color = self.colorHighlight;
            }
        };

        this.onLeftClick = function(event) {
            if (!self.showInfo) return;

            // If a feature was previously selected, undo the highlight
            if (Cesium.defined(selected.feature)) {
                try {
                    selected.feature.color = selected.originalColor;
                } catch (ex) {}
                selected.feature = undefined;
            }

            // Pick a new feature
            var pickedFeature = viewer.scene.pick(event.position);
            if (!Cesium.defined(pickedFeature) && self.orginClickHandler) {
                self.orginClickHandler(event);
                return;
            }

            // Select the feature if it's not already selected
            if (selected.feature === pickedFeature) {
                return;
            }
            self.showTilesParts(pickedFeature);

            if (!Cesium.defined(pickedFeature.getProperty))
                return;

            selected.feature = pickedFeature;

            // Save the selected feature's original color
            if (pickedFeature === highlighted.feature) {
                Cesium.Color.clone(highlighted.originalColor, selected.originalColor);
                highlighted.feature = undefined;
            } else {
                Cesium.Color.clone(pickedFeature.color, selected.originalColor);
            }

            // Highlight newly selected feature
            pickedFeature.color = self.colorSelected;

            // Set feature infobox description
            var featureName = pickedFeature.getProperty('name');
            selectedEntity.name = featureName;
            selectedEntity.description = 'Loading <div class="cesium-infoBox-loading"></div>';

            viewer.selectedEntity = selectedEntity;


            // 普通3dtiles 获取属性表格
            var arr = self.getBimAttr(pickedFeature);
            if (!arr || arr.length == 0) {
                arr = [];
                var names = pickedFeature._content.batchTable.getPropertyNames(pickedFeature._batchId);
                for (var i = 0; i < names.length; i++) {
                    var n = names[i];
                    if (!pickedFeature.hasProperty(n)) continue;

                    var val = pickedFeature.getProperty(n);
                    if (val == null || val == "") continue;
                    arr.push({ name: n, value: val });
                }
            }
            if (!arr || arr.length == 0) return;

            var html = '<table class="cesium-infoBox-defaultTable"><tbody>';
            for (var i = 0; i < arr.length; i++) {
                var item = arr[i];

                if (item.type == "group")
                    html += '<tr><th colspan="2">' + item.name + '</th></tr>';
                else if (item.value)
                    html += '<tr><th>' + item.name + '</th><td>' + item.value + '</td></tr>';
            }
            html += '</tbody></table>';

            if (viewer.infoBox) {
                //infobox方式显示  
                selectedEntity.description = html;

            } else {
                //popup方式显示  
                var cartesian = mars3d.point.getCurrentMousePosition(viewer.scene, event.position);
                setTimeout(function() {
                    viewer.mars.popup.show({
                        id: "bim",
                        popup: {
                            html: html,
                            anchor: [0, -15]
                        }
                    }, cartesian);
                }, 200);
            }

        }


        var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        handler.setInputAction(this.onMouseMove, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        handler.setInputAction(this.onLeftClick, Cesium.ScreenSpaceEventType.LEFT_CLICK);

        this.handler = handler;
    },
    setMouseOver: function(v) {
        if (v) {
            this.handler.setInputAction(this.onMouseMove, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        } else {
            this.restoreHighlight();

            this.nameOverlay.style.display = 'none';
            this.handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        }
    },

    showTilesParts: function(pickedObject) {
        //primitive对象 
        if (pickedObject && Cesium.defined(pickedObject.primitive) &&
            pickedObject.primitive._config && pickedObject.primitive._config.scenetree) {
            var tilesParts = 'widgetsTS/tilesParts/widget.js';

            if (mars3d.widget.isActivate(tilesParts)) {
                var parts = mars3d.widget.getClass(tilesParts);
                if (parts.config.layerWork == pickedObject.primitive._config._layer)
                    return; //当前已激活,并且单击了相同模型时跳出
            }
            mars3d.widget.activate({
                name: pickedObject.primitive._config.name + " 构件",
                uri: tilesParts,
                layerWork: pickedObject.primitive._config._layer,
                scenetree: pickedObject.primitive._config.scenetree,
                disableOhter: false
            });
        }
    }
};